<template>
  <!--页面搭建-杜思成-->
  <layout-card v-model="search" :filters="ismapOptions" headline="信息列表" headtitle=" " :hasButton="true"
    @search-change="getData" @search-reset="searchReset">
    <template #action>
      <el-button type="primary" @click="handleExport">模板下载</el-button>
      <el-upload style="display: inline-block; margin-left: 12px; margin-right: 12px" ref="upload" :auto-upload="false"
        :show-file-list="false" :on-change="handleImport">
        <el-button type="primary">导入</el-button>
      </el-upload>
      <el-button type="primary" @click="handleCreate('create')">新建规则</el-button>
    </template>
    <table-common :height="tableHeight" :columns="mapListColumns" :loading="loading" :pagination="pager"
      :table-data="tabledata" size="large" @current-change="changeCurrent" @size-change="changePageSize">
      <template #tsharGrade="{ row }">
        <el-text v-if="row.tsharGrade == '1'">一般隐患</el-text>
        <el-text v-if="row.tsharGrade == '2'">严重隐患</el-text>
        <el-text v-if="row.tsharGrade == '3'">较大隐患</el-text>
        <el-text v-if="row.tsharGrade == '4'">重大隐患</el-text>
      </template>
      <template #tsharRules="{ row }">
        <el-text v-if="row.tsharRules === '0'">按期整改反馈并通过</el-text>
        <el-text v-if="row.tsharRules === '1'">未按期整改并进行反馈</el-text>
        <el-text v-if="row.tsharRules === '2'">按期整改反馈但未通过完成隐患关闭</el-text>
      </template>
      <template #action="{ row }">
        <!-- 自定义操作栏示例  -->
        <el-button class="link-btn" @click="handleView(row)" link type="primary">查看</el-button>
        <el-button class="link-btn" @click="handleEdit(row)" link type="primary">编辑</el-button>
        <el-popconfirm title="是否删除?" confirmButtonText="确定" cancelButtonText="取消" @confirm="() => DeletRow(row)">
          <template #reference>
            <!--            row.id === formItem.ruleId && formItem.isSave-->
            <el-button :disabled="array.find(item => item.tsharId === row.id)?.isSave" class="link-btns" link
              type="danger">删除</el-button>
          </template>
        </el-popconfirm>
      </template>
    </table-common>
  </layout-card>
  <!-- 新建弹窗开始 -->
  <el-dialog v-model="thresholdDialogVisible" @close="cancel(ruleFormRef)" :title="addTilte" width="500" center
    align-center>
    <el-form :rules="rules" :model="formItem" ref="ruleFormRef">
      <div style="margin-left: 20px">
        <el-form-item label="隐患分类：" prop="tsharClassify" required>
          <el-text v-if="actionType === 'view'">{{ formItem.tsharClassify }}</el-text>
          <el-input v-else v-model="formItem.tsharClassify" placeholder="请输入"></el-input>
        </el-form-item>
      </div>
      <div style="margin-left: 20px">
        <el-form-item label="隐患等级：" prop="tsharGrade" required>
          <div v-if="actionType === 'view'">
            <el-text v-if="formItem.tsharGrade == '1'">一般隐患</el-text>
            <el-text v-else-if="formItem.tsharGrade == '2'">严重隐患</el-text>
            <el-text v-else-if="formItem.tsharGrade == '3'">较大隐患</el-text>
            <el-text v-else-if="formItem.tsharGrade == '4'">重大隐患</el-text>
          </div>
          <el-select v-else v-model="formItem.tsharGrade" style="width: 337.63px">
            <el-option label="一般隐患" value="1"></el-option>
            <el-option label="严重隐患" value="2"></el-option>
            <el-option label="较大隐患" value="3"></el-option>
            <el-option label="重大隐患" value="4"></el-option>
          </el-select>
        </el-form-item>
      </div>
      <div style="margin-left: 20px">
        <el-form-item label="评分规则：" prop="tsharRules" required>
          <div v-if="actionType === 'view'" v-for="item in codePointArray">
            <el-text v-if="item.value == formItem.tsharRules">{{ item.text }}</el-text>
          </div>

          <el-select v-else v-model="formItem.tsharRules" style="width: 337.63px">
            <el-option v-for="item in codePointArray" :label="item.text" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
      </div>
      <div style="margin-left: 20px">
        <el-form-item label="扣分数值：" prop="tsharScores" required>
          <el-text v-if="actionType === 'view'">{{ formItem.tsharScores }}</el-text>
          <el-input-number v-else ref="deductNumberInput" v-model="formItem.tsharScores" style="width: 337.63px"
            placeholder="请设置分值" controls-position="right" min="0" max="100"></el-input-number>
        </el-form-item>
      </div>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <div v-if="actionType === 'view'">
          <el-button type="primary" @click="thresholdDialogVisible = false">关闭</el-button>
        </div>
        <div v-else>
          <el-button @click="cancel(ruleFormRef)">取消</el-button>
          <el-button v-if="actionType === 'edit'" type="primary" @click="save(ruleFormRef)">保存</el-button>
          <el-button type="primary" @click="certain(ruleFormRef)">确定</el-button>
        </div>
      </span>
    </template>

  </el-dialog>
  <!-- 设置弹窗结束 -->
</template>

<script lang="ts" setup>

import { computed, ref, reactive, onMounted, onBeforeMount, nextTick } from "vue";
import LayoutCard from "@/components/LayoutCard/index.vue";
import TableCommon from "@/components/TableCommon/index.vue";
import {
  initAssessRule,
  addRule,
  editRule,
  deleteRule,
  download,
  listImport
} from "@/api/secure/assessRule";
import {
  initCodePoint
} from "@/api/secure/assessInfo";
import { mapListColumns } from "@/views/secure/defect/assessRule/config/columns";
import {
  mapOptions,
} from "@/views/secure/defect/assessRule/config/filters";
import {
  dayjs,
  ElMessage,
  UploadFile, UploadInstance,
} from "element-plus";

import type {
  FormInstance, FormRules
}
  from "element-plus"
import { useStore } from "vuex";
import { getUserInfo } from "@/api/secure/catalogue";

const tableHeight = ref(window.innerHeight - 442)
const actionType = ref('')
const ruleFormRef = ref<FormInstance>()

const formItem = ref({
  tsharId: '',
  tsharClassify: '',
  tsharGrade: '',
  tsharRules: '',
  tsharScores: '',
  tsharPerson:'',
  isSave: false
})

const validateEarlyType = (rule: any, value: any, callback: any) => {
  if (formItem.value.tsharClassify === '') {
    callback(new Error('请输入隐患类型'))
  } else {
    callback()
  }
}
const validateEarlyLevel = (rule: any, value: any, callback: any) => {
  if (formItem.value.tsharClassify === '') {
    callback(new Error('请选择隐患级别'))
  } else {
    callback()
  }
}
const validateCodePoint = (rule: any, value: any, callback: any) => {
  if (formItem.value.tsharRules === '') {
    callback(new Error('请选择评分标准'))
  } else {
    callback()
  }
}
const validateDeductNumber = (rule: any, value: any, callback: any) => {
  if (formItem.value.tsharScores === '') {
    callback(new Error('请输入扣分数值'))
  }
  if (formItem.value.tsharScores < '0' || formItem.value.tsharScores > '100') {
    callback(new Error('请输入0-100之间的数'))
  } else {
    callback()
  }
}

const rules = reactive<FormRules<typeof formItem>>({
  tsharClassify: [
    // {required: true, validator: validateEarlyType, trigger: 'blur'}
    { required: true, message: '请输入隐患类型', trigger: 'blur' }
  ],
  tsharGrade: [
    { required: true, message: '请选择隐患级别', trigger: 'change' }
  ],
  tsharRules: [
    { required: true, message: '请选择评分标准', trigger: 'change' }
  ],
  tsharScores: [
    // {required: true, message: '请输入扣分数值', trigger: 'blur'},
    { required: true, validator: validateDeductNumber, trigger: 'blur' }
  ],
})


const loading = ref(false)
const deductNumberInput = ref()
const ismapOptions = ref(mapOptions);
const thresholdDialogVisible = ref(false);


const addTilte = ref(""); // 弹出框名称

// 分页和数据展示参数
const current = ref(1);
const pageSize = ref(10);
const total = ref(0);
const tabledata = ref([]);
interface Search {
  earlyType?: string,
  creatTime?: string[],
  earlyLevel?: string
}
const search = ref<Search>({});

const pager = computed(() => ({
  currentPage: current.value,
  pageSize: pageSize.value,
  total: total.value,
  pageCount:
    Math.ceil(total.value / pageSize.value) === 0
      ? 1
      : Math.ceil(total.value / pageSize.value),
}));
const searchCondition = ref<ListParams>({
  pageNum: current.value,
  pageSize: pageSize.value,
  condition: search.value
})
// const codePointArray = ref(["按期整改反馈并通过","未按期整改并进行反馈","按期整改反馈但未通过完成隐患关闭"])
const codePointArray = ref([
  {
    text: "按期整改反馈并通过",
    value: 0
  },
  {
    text: "按期整改反馈但未通过完成隐患关闭",
    value: 1
  },
  {
    text: "未按期整改并进行反馈",
    value: 2
  }
])

/**
 * @functionName 分页、查询、排序、删除功能
 * @author 杜思成
 * @date 2023-08-08 17:46:09
 * @version V1.0.0
 */
const changeCurrent = (value: number) => {
  current.value = value;
  searchCondition.value.pageNum = value
  getData()
};
const changePageSize = (size: number) => {
  pageSize.value = size;
  searchCondition.value.pageSize = size
  getData()
};
const order = ref([
  {
    column: "state",
    method: "asc",
  },
  {
    column: "lastUpdateTime",
    method: "desc",
  },
]);

onMounted(() => {
  // getCodePoint()
  getData()
  // console.log(userInfo.value)
  // console.log(Users)
})

const getCodePoint = () => {
  initCodePoint().then(res => {
    codePointArray.value = res.data
  }).catch(res => {
    console.log(res)
  })
}
/**
 * @functionName 获取数据
 * @author 彭庆楠
 * @date 2023-08-08 17:47:31
 * @version V1.0.0
 * @return
 */
const getData = async (data: FilterDataType) => {
  // loading.value = true
  // search.value = data
  // searchCondition.value.condition = data
  const params = {
    tsharClassify: search.value?.earlyType,
    // tshar_ut: search.value?.creatTime,
    tsharGrade: search.value?.earlyLevel,
    // startTime: search.value?.creatTime?.[0],
    // endTime: search.value?.creatTime?.[1],
  }
  const playout = {
    page: {
      page: current.value - 1,
      size: pageSize.value
    },
    myTime2: {
    startTime: search.value?.creatTime?.[0],
    endTime: search.value?.creatTime?.[1],
    },
    tcdmSecureHazardAssessmentRules: params,
  }
  initAssessRule(playout).then(res => {
    tabledata.value = res.content
    // loading.value = false
    total.value = res.totalElements
    // current.value = res.data.pageNum
  }).catch(res => {
    console.log(res)
  })
};

const username = ref("")
const getUser = (id: any) => {
  getUserInfo(id).then(res => {
    username.value = res.data.userName
  }).catch(res => {
    console.log(res)
  })
  return username.value
}
// 删除
const DeletRow = (row: any) => {
  console.log(row)
  formItem.value.tsharId = row.tsharId
  deleteRule(formItem.value).then(res => {
    // if (res.message === "success") {
      getData()
      console.log(res)
    //   ElMessage({
    //     message: '删除成功',
    //     type: 'success',
    //   })
    // } else {
    //   ElMessage({
    //     message: '删除失败',
    //     type: 'error',
    //   })
    // }
  }).catch(res => {
    console.log(res)
  })
};

/**
 * @functionName 新增、编辑弹出框
 * @param {any} val 判断打开那个弹窗
 * @description
 * @author 彭庆楠
 * @date 2023-08-08 17:53:22
 * @version V1.0.0
 * @return
 */
const handlePopup = (val: any) => {
  actionType.value = val
  // 新建规则
  if (val === "create") {
    // 弹窗标题
    thresholdDialogVisible.value = true;
    addTilte.value = "新建";
  }
  // 查看
  if (val === "view") {
    // 弹窗标题
    thresholdDialogVisible.value = true;
    addTilte.value = "查看";
  }
  // 编辑
  if (val === "edit") {
    // 弹窗标题
    thresholdDialogVisible.value = true;
    addTilte.value = "编辑";
  }
};

/**
 * 下载
 */
const handleExport = () => {
  download().then(res => {
    const link = document.createElement("a");
    link.href = URL.createObjectURL(new Blob([res]));
    link.download = "安全隐患考核规则导出模板.xlsx";
    link.click();
  }).catch(res => {
    console.log(res)
    ElMessage.error('导出失败')
  })
}

const Users = useStore().getters["user/getUserInfo"]
const store = useStore()
const userInfo = computed(() => store.state.user.userInfo);
const upload = ref<UploadInstance>()
const btnLoading = ref(false) // 导入按钮加载状态

/**
 * 导入
 */
const handleImport = (file: { name: string; raw: string | Blob; }) => {
  if (!btnLoading.value) {
    btnLoading.value = true
    if (!file) {
      return false;
    } else if (!/.(xls|xlsx)$/.test(file.name.toLowerCase())) {
      ElMessage.error("上传格式不正确,请上传xls或者xlsx格式");
      return false;
    }
    const formData = new FormData()
    formData.append('multipartFile', file.raw)
    formData.append('id', userInfo.value.userId)
    formData.append('name', userInfo.value.name)
    listImport(formData).then((res: any) => {
      if (res.code === '1') {
        console.log(res)
        ElMessage.success(res.message)
        current.value = 1
        pageSize.value = 10
        getData()
        setTimeout(() => {
          upload.value!.clearFiles()
        }, 1000)
      } else {
        ElMessage.error(res.message)
      }
      btnLoading.value = false
    }).catch((res) => {
      ElMessage.error(res.message)
      btnLoading.value = false
      console.log(res)
    })
    setTimeout(() => {
      upload.value!.clearFiles()
    }, 1000)
  }
}

const certain = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      if (addTilte.value === "新建") {
        addRule(formItem.value).then(res => {
          console.log(res)
          // if (res) {
            getData()
            thresholdDialogVisible.value = false
          //   ElMessage({
          //     message: res.message,
          //     type: 'success',
          //   })
          // } else {
          //   ElMessage({
          //     message: res.message,
          //     type: 'error',
          //   })
          // }
        }).catch(res => {
          console.log(res)
          ElMessage({
            message: "添加失败",
            type: 'error',
          })
        })
      }
      if (addTilte.value === "编辑") {
        editRule(formItem.value).then(res => {
          // if (res.message === "success") {
            getData()
            thresholdDialogVisible.value = false
          //   ElMessage({
          //     message: '修改成功',
          //     type: 'success',
          //   })
            if (actionType.value === "edit") {
              let obj = array.value.find(item => item.tsharId === formItem.value.tsharId)
              obj.isSave = false
            }
          // } else {
          //   ElMessage({
          //     message: '修改失败',
          //     type: 'error',
          //   })
          // }
        }).catch(res => {
          console.log(res)
        })
      }
    } else {
      console.log('error submit!', fields)
    }
  })
}

// const certain = () => {
//   if (addTilte.value === "新建"){
//     addRule(formItem.value).then(res=> {
//       if (res.message === "success"){
//         getData()
//         thresholdDialogVisible.value = false
//         ElMessage({
//           message: '添加成功',
//           type: 'success',
//         })
//       }else {
//         ElMessage({
//           message: '添加失败',
//           type: 'error',
//         })
//       }
//     }).catch(res => {
//       console.log(res)
//     })
//   }
//   if (addTilte.value === "编辑"){
//     editRule(formItem.value).then(res => {
//       if (res.message === "success"){
//         getData()
//         thresholdDialogVisible.value = false
//         ElMessage({
//           message: '修改成功',
//           type: 'success',
//         })
//       }else {
//         ElMessage({
//           message: '修改失败',
//           type: 'error',
//         })
//       }
//     }).catch(res => {
//       console.log(res)
//     })
//   }
// }
// const cancel = () => {
//   formItem.value.isSave = false
//   thresholdDialogVisible.value = false
// }
//
// const save = () => {
//   formItem.value.isSave = true
//   thresholdDialogVisible.value = false
// }

// 保存的元素
const array = ref([])
const save = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      formItem.value.isSave = true
      let temp = { ...formItem.value }
      let obj = array.value.find(item => item.ruleId === temp.ruleId)
      if (obj) {
        let index = array.value.indexOf(obj)
        console.log(index)
        array.value.splice(index, 1)
      }
      array.value.push(temp)
      console.log(array.value)
      thresholdDialogVisible.value = false
    } else {
      console.log('error submit!', fields)
    }
  })
}

const cancel = (formEl: FormInstance | undefined) => {
  thresholdDialogVisible.value = false
  if (!formEl) return
  formEl.resetFields()
}
// 新建规则
const handleCreate = async (row: any) => {
  formItem.value.tsharId = '',
    formItem.value.tsharRules = '',
    formItem.value.tsharScores = '',
    formItem.value.tsharGrade = '',
    formItem.value.tsharClassify = '',
    handlePopup("create");
};
// 查看
const handleView = async (row: any) => {
  console.log(row)
  formItem.value.tsharId = row.tsharId,
    formItem.value.tsharRules = parseInt(row.tsharRules),
    formItem.value.tsharScores = row.tsharScores,
    formItem.value.tsharGrade = row.tsharGrade,
    formItem.value.tsharClassify = row.tsharClassify,
    console.log(formItem.value);
  handlePopup("view");
};
// 编辑
const handleEdit = async (row: any) => {
  // let temp = array.value.find(item => item.ruleId === row.id)
  console.log(row);
  
  console.log(array.value);
  
  // if (temp) {
    formItem.value.tsharId = row.tsharId,
    formItem.value.tsharRules = parseInt(row.tsharRules),
    formItem.value.tsharScores = row.tsharScores,
    formItem.value.tsharGrade = row.tsharGrade,
    formItem.value.tsharClassify = row.tsharClassify,
    console.log(formItem.value);
  // } else {
  //   formItem.value.ruleId = row.id;
  //   formItem.value.codePoint = parseInt(row.codePoint);
  //   // formItem.value.deductNumber = row.deductNumber.toString();
  //   formItem.value.deductNumber = parseInt(row.deductNumber);
  //   formItem.value.earlyLevel = row.earlyLevel;
  //   formItem.value.earlyType = row.earlyType;
  // }
  // if (formItem.value.ruleId !== row.id || !formItem.value.isSave){
  //   formItem.value.ruleId = row.id;
  //   formItem.value.codePoint = parseInt(row.codePoint);
  //   formItem.value.deductNumber = row.deductNumber.toString();
  //   formItem.value.earlyLevel = row.earlyLevel;
  //   formItem.value.earlyType = row.earlyType;
  //   formItem.value.isSave = false;
  // }
  handlePopup("edit");
};

const FilterRef = ref({});

/**
 * @functionName 重置功能
 * @param {FilterDataType} data
 * @description
 * @author 杜思成
 * @date 2023-08-17 17:55:57
 * @version V1.0.0
 * @return
 */
const searchReset = (data: FilterDataType) => {
  search.value = data;
  pager.value.currentPage = 1;
  pager.value.pageSize = 10;
  getData()
};
</script>
<style scoped>
.link-btn {
  color: #2F7DF1;
}

.link-btns {
  color: #F24A45;
}
</style>
